﻿//=============================================================
// Copyright (C) 2011 iSun Studio
// 作 者：江怀玉
// 日 期：2011-10-11
// 描 述: 通用的单笔数据增删改
//        json:前端提交的数据
//        action:操作,insert,update,delete
//        entity:实体对象名称
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
// 1.00   2011/10/11   江怀玉           
//=============================================================
using System;
using System.Web;
using System.Text;
using System.Web.Script.Serialization;
using iSun.Common;

using iSun.Model;
using iSun.BLL.Base;
using System.Collections.Generic;

namespace iSun.Web.UI.Controls
{
    public partial class DataSave : BasePage
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            //DateTime dt = DateTime.Now;
            string strAction = this.GetStringFromQueryString("action", "");
            string strEntity = this.GetStringFromQueryString("entity", "");
            string strTable = this.GetStringFromQueryString("table", "");
            string strFrom = this.GetStringFromQueryString("from", "");
            ///用于表单自定义
            string strFormID = this.GetStringFromQueryString("fromid", Guid.Empty.ToString());
            string flag = this.GetStringFromQueryString("flag", "");
            string strJson = "";
            if (flag == "1")
            {  
                string Forms = iSunContext.Request.Form[0].ToString();
                strJson = Forms;               
            }
            else
            {
                strJson = this.GetStringFromQueryString("json", "").Replace("[@@]", "\\");
            }

            CreateBussniess(strEntity);
            BaseEntity instance = null;
            try
            {
                instance = (BaseEntity)Globals.JSONtoObject(strEntity, strJson);
            }
            catch { }
            if (instance == null)
            {
                strTable = strEntity;
            }
            if (strTable =="" || "insert,update,delete".IndexOf(strAction)<0 ) // 有实体的
            {
                string msg = "";
                switch (strAction)
                {
                    case "":
                        InsertOrUpdate(strEntity, strJson.Replace("[A]", "&"), strAction);
                        break;
                    case "insert":
                        try
                        {
                            InsertOrUpdate(strEntity, strJson.Replace("[A]", "&"), strAction);
                        }
                        catch (Exception ex)
                        {
                            msg = ex.Message;
                        }
                        HttpContext.Current.Response.Write(msg);
                        break;
                    case "delete":
                        delete(strEntity, strJson);
                        break;
                    case "setRight":
                        SetRight(strJson);
                        break;
                    case "setQuery":
                        SetQuery(strJson);
                        break;
                    case "setTableStruc":
                        try
                        {
                            SetTableStruc(strJson);
                        }
                        catch (Exception ex)
                        {
                            msg = ex.Message;
                        }
                        HttpContext.Current.Response.Write(msg);
                        break;
                    case "deleteFile":
                        string path = this.GetStringFromQueryString("path", "");
                        string file = this.GetStringFromQueryString("file", "");
                        DeleteFile(path, file);
                        break;
                    default:
                        InsertOrUpdate(strEntity, strJson.Replace("[A]", "&"), strAction);
                        break;
                }
            }
            else // 没有实体的
            {
               switch (strAction)
                {
                    case "insert":
                        Insert(strTable, strJson.Replace("[A]", "&"));
                        break;
                    case "update":
                        Update(strTable, strJson.Replace("[A]", "&"));
                        break;
                    case "delete":
                        Delete(strTable, strJson);
                        break;
                }
            }
        }


        /// <summary>
        /// 创建业务逻辑实例
        /// </summary>
        /// <param name="entityName"></param>
        private void CreateBussniess(string entityName)
        {
            this._bll = BaseBussnies.CreateInstance(entityName);
        }

        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        /// <param name="action"></param>
        private void InsertOrUpdate(string strEntity, string strJson,string action)
        {
            
            BaseEntity instance = (BaseEntity)Globals.JSONtoObject(strEntity, strJson);
            _bll.entity = instance;
            System.Guid? keyValue = instance.GetKeyFieldValue();
            //BaseEntity item = instance.
            //数据验证
            string strMsg = instance.CheckData();
            if (strMsg != "")
            {
                HttpContext.Current.Response.Write(strMsg);
                return;
            }
            strMsg = instance.GetDataCheckMessage();
            if (strMsg != "")
            {
                HttpContext.Current.Response.Write(strMsg);
                return;
            }
            bool b;
            if (action == "")
            {
                if (instance.GetKeyFieldValue() == new System.Guid())
                {
                    action = "insert";
                }
            }
            string checkResult = _bll.CheckData();
            if (false == string.IsNullOrEmpty(checkResult))
            {
                HttpContext.Current.Response.Write(checkResult);
                return;
            }

            //// 如果是批量数据操作
            if (this.GetStringFromQueryString("isBatch", "false") == "true")
            {
                Insert(strEntity, strJson);
                return;
            }


            strMsg = "";
            //instance.Save();
            if (action == "insert")
            {
                if (null == (Globals.GetPropertyValue(instance, "AddUser") as Guid?)||(Globals.GetPropertyValue(instance, "AddUser") as Guid?) == Guid.Empty)
                {
                    Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                    Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);
                }


                b = _bll.Insert(out strMsg);
                if (EntityName == "SysTable")
                {
                    BLL.Base.DBTable dbTable = SqlDBTable.Instance;
                    dbTable.CreateTable((instance as SysTable).TableName);
                }
            }
            else
            {
                if (null == (Globals.GetPropertyValue(instance, "AddUser") as Guid?) || (Globals.GetPropertyValue(instance, "AddUser") as Guid?) == Guid.Empty)
                {
                    Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                    Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);
                }
                checkResult = _bll.EditCheckData();
                if (false == string.IsNullOrEmpty(checkResult))
                {
                    HttpContext.Current.Response.Write(checkResult);
                    return;
                }
                b = _bll.Update(out strMsg);
            }
            if (b)
            {
                HttpContext.Current.Response.Write("1");
            }
            else
            {
                HttpContext.Current.Response.Write(strMsg);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        private void delete(string strEntity, string strJson)
        {
            string checkResult = _bll.DeleteCheckData();
            if (false == string.IsNullOrEmpty(checkResult))
            {
                HttpContext.Current.Response.Write(checkResult);
                return;
            }
            BaseEntity instance = (BaseEntity)iSun.Common.Reflection.CreateEntitysInstance(strEntity);
            BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(instance);
            string key = instance.getKey();
            if (string.IsNullOrEmpty(strJson))
            {
                strJson = this.GetStringFromQueryString("id", "");
                bll.Delete(key + "='" + strJson + "'");
                HttpContext.Current.Response.Write("1");
            }
            else
            {
                string[] strarr = strJson.Split(',');
                foreach (var s in strarr)
                {
                    bll.Delete(key + "='" + s + "'");
                }
                HttpContext.Current.Response.Write("1");
            }
        }

        #region 系统设置
        /// <summary>
        /// 设置权限
        /// </summary>
        /// <param name="strJson"></param>
        private void SetRight(string strJson)
        {
            //var list = (List<V_FunctionRight>)Globals.JSonToObject<List<V_FunctionRight>>(strJson);
            //string strSql = "update SysRoleFunction set BarItems='{0}',OperateRangeType='{2}',Depts='{3}',Condition='{4}' where RoleFunctionID='{1}'\n";
            //StringBuilder sSql = new StringBuilder("");
            //foreach (var item in list)
            //{
            //    sSql.Append(string.Format(strSql, item.BarItem ,item.RoleFunctionID,item.OperateRangeType,item.Depts,item.Condition));
            //}
            //BaseBussnies bll = new BaseBussnies();
            //if (sSql.ToString() == "")
            //{
            //    ZXContext.Response.Write("没有数据!");
            //    return;
            //}
            //int i = bll.RunSqlCommand(sSql.ToString());
            //if (i > 0)
            //{
            //    ZXContext.Response.Write("1");
            //}
            //else
            //{
            //    //写日志
            //    WriteExpLog();
            //    ZXContext.Response.Write("0");
            //}
        }
      

        private void BatchSave(string strJson)
        {
            
        }
        /// <summary>
        /// 设置表结构
        /// </summary>
        /// <param name="strJson"></param>
        /// <summary>
        /// 设置表结构
        /// </summary>
        /// <param name="strJson"></param>
        public void SetTableStruc(string strJson)
        {
            List<SysTableField> list = Globals.JSonToObject<List<SysTableField>>(strJson);
            iSun.BLL.Base.DBTable dbTable = SqlDBTable.Instance;
            foreach (SysTableField entity in list)
            {
                if (entity.TableFieldID == Guid.Empty)
                {
                    string strFiled = entity.FiledType;
                    switch (strFiled.ToLower())
                    {
                        case "varchar":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;
                        case "nvarchar":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;
                        case "char":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;
                        case "nchar":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;
                        case "ntext":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;

                        case "bigint":
                            strFiled = entity.FiledType;
                            break;
                        case "int":
                            strFiled = entity.FiledType;
                            break;
                        case "bit":
                            strFiled = entity.FiledType;
                            break;
                        case "datetime":
                            strFiled = entity.FiledType;
                            break;
                        case "smalldatetime":
                            strFiled = entity.FiledType;
                            break;
                        case "date":
                            strFiled = entity.FiledType;
                            break;
                        case "uniqueidentifier":
                            strFiled = entity.FiledType;
                            break;
                        case "money":
                            strFiled = entity.FiledType;
                            break;

                        case "binary":
                            strFiled = entity.FiledType;
                            break;
                        case "float":
                            strFiled = entity.FiledType;
                            break;
                        case "image":
                            strFiled = entity.FiledType;
                            break;
                        case "numeric":
                            strFiled = entity.FiledType + "(" + entity.Length + ")";
                            break;
                        case "real":
                            strFiled = entity.FiledType;
                            break;
                        default:
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;

                    }


                    dbTable.AddCol(entity.TableName, entity.FieldName, strFiled);
                    dbTable.AddColNotes(entity.TableName, entity.FieldName, entity.Notes);
                }

            }
            iSunContext.Response.Write("1");
        }
        

        /// <summary>
        /// 创建表
        /// </summary>
        /// <param name="TableName"></param>
        public void SetTable(string TableName)
        {
            BLL.Base.DBTable dbTable = SqlDBTable.Instance;
            dbTable.CreateTable(TableName);
        }

        /// <summary>
        /// 设置查询
        /// </summary>
        /// <param name="strJson"></param>
        private void SetQuery(string strJson)
        {
            QuerySolution entity = (QuerySolution)Globals.JSonToObject<QuerySolution>(strJson);
            entity.BaseEntityState = WorkState.New;
            entity.EntityName = this.EntityName;
            entity.FunctionID = this.FunctionID;
            entity.AddUser = this.UserId;
            entity.AddTime = DateTime.Now;
            string action="";

            if(entity.QueryId==null||entity.QueryId == Guid.Empty)
            {
                action = "insert";
                entity.QueryId = Guid.Empty;
            }

            //BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            _bll.entity = entity;
            if (entity.IsDefault == "Y")
            {
                _bll.RunSqlCommand("update Set_QuerySolution set IsDefault='N' where AddUser='" + this.UserId + "' and FunctionID='" + entity.FunctionID + "'");
            }
            bool b;
            if (action == "insert")
            {

                b = _bll.Insert();
            }
            else
            {
                b = _bll.Update();
            }
            if (b)
            {
                Response.Write("1");
            }
            else
            {
                Response.Write("0");
            }
        }


        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="File"></param>
        private void DeleteFile(string FilePath,string File)
        {
            string path = this.MapPath(FilePath);
            System.IO.File.Delete(path + File);
        }
        #endregion
        #region No Entity
        /// <summary>
        /// 实现没有实体的操作
        /// </summary>
        /// <param name="table"></param>
        /// <param name="json"></param>
        public void Insert(string table, string json)
        {
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string detailTable = GetDetailTable(GetStringFromQueryString("formid",Guid.Empty.ToString()), table);
            string[] strKeyArrary = instance.GetKey();
            if (strKeyArrary != null)
            {
                instance.TableKey = strKeyArrary[0];
                instance.KeyType = strKeyArrary[1];
            }
            instance.CreateDT(); 
            string[] s1 = { "[@@@]" };
            string[] strArray = json.Split(s1, StringSplitOptions.None);
            instance.EntityJson = strArray[0];//json;// ZX.Common.Globals.DataRowToJSON(instance.DRow);
            instance.FieldValue = iSun.Common.Globals.ConvertToDictionary(instance.EntityJson);
            if(instance.FieldValue.ContainsKey("RecID")){
                instance.FieldValue.Remove("RecID");
            }
            instance.SetValue(instance.FieldValue);
            //instance.SetPropertyValue("", "");
            StringBuilder sqlCommand = new StringBuilder("").AppendLine();
            BaseBussnies bll = new BaseBussnies(instance);
            sqlCommand.Append(bll.GetSqlCommand(instance));
            string strMsg = "";
            if (!string.IsNullOrEmpty(detailTable))
            {
                if (strArray.Length > 1)
                {
                    JavaScriptSerializer s = new JavaScriptSerializer();
                    object[] list = (object[])s.DeserializeObject(strArray[1]);
                    foreach (object o in list)
                    {
                        DataTableBaseEntity DetailInstance = new DataTableBaseEntity();
                        DetailInstance.TableName = detailTable;
                        strKeyArrary = DetailInstance.GetKey();
                        if (strKeyArrary != null)
                        {
                            DetailInstance.TableKey = strKeyArrary[0];
                            DetailInstance.KeyType = strKeyArrary[1];
                        }
                        DetailInstance.CreateDT();
                        Dictionary<string, object> d = o as Dictionary<string, object>;
                        DetailInstance.FieldValue = d;
                        DetailInstance.SetValue(d);
                        if(DetailInstance.FieldValue.ContainsKey("RecID")){
                        DetailInstance.FieldValue.Remove("RecID");
                        }
                        if (((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)DetailInstance).TableKey] == null || ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)instance).TableKey].ToString() != string.Empty)
                        {
                            ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)DetailInstance).TableKey] = Guid.NewGuid();
                        }
                        //entity.SetFieldValue(entity, e.FieldName, MasterEntity.GetKeyFieldValue());
                        //DetailInstance.SetFieldValue(DetailInstance, DetailInstance.GetFKey()[0].FieldName, instance.GetKeyFieldValue());
                        bll.entity = DetailInstance;
                        sqlCommand.Append(bll.GetSqlCommand(DetailInstance));
                    }
                    int i = bll.RunSqlCommand(sqlCommand.ToString(), out strMsg);
                    if (i > -1)
                    {
                        iSunContext.Response.Write("1");
                        return;
                    }
                    else
                    {
                        iSunContext.Response.Write(strMsg);
                        return;
                    }
                }
            }
            strMsg = "";
            if (bll.Insert(out strMsg))
            {
                iSunContext.Response.Write("1");
            }
            else
            {
                iSunContext.Response.Write(strMsg);
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="table"></param>
        /// <param name="json"></param>
        public void Update(string table, string json)
        {
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string detailTable = GetDetailTable(GetStringFromQueryString("formid", Guid.Empty.ToString()), table);
            string[] strArrary = instance.GetKey();
            if (strArrary != null)
            {
                instance.TableKey = strArrary[0];
                instance.KeyType = strArrary[1];
            }
            instance.CreateDT();
            string[] s1 = { "[@@@]" };
            string[] strArray = json.Split(s1, StringSplitOptions.None);
            instance.EntityJson = strArray[0];// ZX.Common.Globals.DataRowToJSON(instance.DRow);
            instance.FieldValue = iSun.Common.Globals.ConvertToDictionary(instance.EntityJson);
            instance.SetValue(instance.FieldValue);
            StringBuilder sqlCommand = new StringBuilder("").AppendLine();
            BaseBussnies bll = new BaseBussnies(instance);
            sqlCommand.Append(bll.GetSqlCommand(instance));
            // 将旧的数据清空
            if (!string.IsNullOrEmpty(detailTable))
            {
                if (strArray.Length > 1)
                {
                    JavaScriptSerializer s = new JavaScriptSerializer();
                    object[] list = (object[])s.DeserializeObject(strArray[1]);
                    int _count = 0;
                    foreach (object o in list)
                    {
                        DataTableBaseEntity DetailInstance = new DataTableBaseEntity();
                        DetailInstance.TableName = detailTable;
                        strArray = DetailInstance.GetKey();
                        if (strArray != null)
                        {
                            DetailInstance.TableKey = strArray[0];
                            DetailInstance.KeyType = strArray[1];
                        }
                        DetailInstance.CreateDT();

                        Dictionary<string, object> d = o as Dictionary<string, object>;
                        DetailInstance.FieldValue = d;
                        DetailInstance.SetValue(d);
                        bll.entity = DetailInstance;
                        // 加入
                        if (_count == 0)
                        {
                            IList<SysTableFKey> fkList = DetailInstance.GetFKey();
                            if (fkList != null)
                            {
                                foreach (var e in fkList)
                                {
                                    if (e.FKTableName == instance.GetTableName())
                                    {
                                        sqlCommand.Append(string.Format("Delete from {0} where {1}", DetailInstance.GetTableName(), e.FieldName + "='" + instance.GetTableIdValue() + "'"));
                                    }

                                }
                            }
                        }
                        _count = 1;
                        sqlCommand.Append(bll.GetSqlCommand(DetailInstance));
                    }
                }
                int i = bll.RunSqlCommand(sqlCommand.ToString());
                Response.Write("1");
                return;
            }
            if (bll.Update())
            {
                iSunContext.Response.Write("1");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="table"></param>
        /// <param name="json"></param>
        public void Delete(string table, string json)
        {
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string[] strArrary = instance.GetKey();
            if (strArrary != null)
            {
                instance.TableKey = strArrary[0];
                instance.KeyType = strArrary[1];
            }
            string[] ids = json.Split(',');
            try
            {
                foreach (string id in ids)
                {
                    instance.Delete(id);
                }
                iSunContext.Response.Write("1");
            }
            catch (Exception e){
                iSunContext.Response.Write(e.Message);
            }
        }
        #endregion


        /// <summary>
        /// 初始数据
        /// </summary>
        /// <param name="strFormID">表单ID</param>
        /// <param name="strEntity">实体名称</param>
        private string GetDetailTable(string strFormID,string strEntity)
        {
            if (strFormID == "")
            {
                strFormID = Guid.Empty.ToString();
            }
            iSun.Entity.SysCustomDefineForm FormEntity = _bll.GetEntityByCondition<iSun.Entity.SysCustomDefineForm>("FormID='" + strFormID + "' or MasterTableName='" + strEntity + "'");
            if (FormEntity != null)
            {
                return GetDetailTable(FormEntity.DetailsJson);
            }
            return "";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="DetailsJson"></param>
        /// <returns></returns>
        private string GetDetailTable(string DetailsJson)
        {
            if (!string.IsNullOrEmpty(DetailsJson))
            {
                IList<SysDetailsItem> list = iSun.Common.Globals.JSonToObject<IList<SysDetailsItem>>(DetailsJson);
                StringBuilder _details = new StringBuilder("");
                foreach (var _detail in list)
                {
                    return _detail.DetailsTableName;

                }
                //DetailsInstance = _details.ToString();
            }
            return "";
        }
    }
}